/**
 * Created by Mark_ren on 2016/10/10.
 * 苟富贵、無相忘
 */
var express = require('express');
var moment = require("moment");
var router = express.Router();
var co = require('co');
var seqModule = require('./createModules');
var seq = new seqModule();

var formidable = require('formidable');
var getIP = require('./getIP');

var fs = require('fs');


//查询(返回点赞评论数)
router.get('/getClassZS', function(req, res, next) {
    co(function () {
        seq.sequelize.query("select class.id,class.TITLE,class.ABSTRACT,class.URL,class.c_type as cType,class.TOP_TIME as topTime,class.PICTURE_URL," +
            "  (select count(id) from qcc_collection where class.id = course_id LIMIT 1) as shoucang," +
            "  (select count(id) from qcc_liked where class.id=course_id LIMIT 1) as dianzan ," +
            "  (select count(id) from qcc_collection where member_id = '"+req.query.userid+"' and class.id = course_id LIMIT 1)as shoucang1," +
            "  (select count(id) from qcc_liked where member_id = '"+req.query.userid+"' and class.id = course_id LIMIT 1) as dianzan1" +
            "  from qcc_classroom as class where class.c_type = "+req.query.cType+"  order by class.TOP_TIME DESC,class.CREATETIME DESC").spread(function(results){
            res.json({"success":true,"rows":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});
//分页
router.get('/getClassPage', function(req, res, next) {
    co(function () {
        var page=parseInt(req.query.page);
        var params={};
        var paramT={};
        var paramU={};
        //根据id
        if(req.query.id != undefined){
            params["id"]=req.query.id;
        }
        //模糊查询
        if(req.query.cTitle != undefined){
            paramU["$like"]="%"+req.query.cTitle+"%";
            params["cTitle"]=paramU;

        }

        params["softDel"]=1;
        paramT["where"]=params;
        paramT["order"]=[["topTime",'DESC'],["createTime",'DESC']];
        if(req.query.page != undefined && req.query.rows !=undefined){
            paramT["offset"]=parseInt(req.query.page);
            paramT["limit"]=parseInt(req.query.rows);
        }
        seq.classModule.findAndCountAll(paramT).then(function(result){
            res.json({"success":true,"page":page,"total":result.count,"result":result.rows});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});

//添加讲堂内容
router.get('/addClass', function(req, res, next) {
    co(function () {
        req.query.createTime=moment().format("YYYY-MM-DD HH:mm:ss");
        seq.classModule.create(req.query).then(function(results){
            res.json({"success":true,"rows":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});

//删除
router.get('/deleteClass', function(req, res, next) {
    co(function () {
        var params=req.query.params;
        var arr=params.split(",");
        var paramT=[arr];
        seq.classModule.destroy({'where':{'id':paramT}}).then(function(results){
            res.json({"success":true,"msg":"删除成功","rows":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'删除失败'});
        console.log(e);
    })
});
// //删除
// router.get('/deleteClass', function(req, res, next) {
//     co(function () {
//         var param_id = req.query.id;
//         // var params=req.query.params;
//         // var arr=params.split(",");
//         // var paramT=[arr];
//         yield seq.classModule.destroy({'where':{'id':param_id}}).then(function(results){
//             res.json({"success":true,"msg":"删除成功","rows":results});
//         });
//     }).catch(function(e) {
//         res.json({'success':false,'msg':'删除失败'});
//         console.log(e);
//     })
// });

//查询大讲堂内容
router.get('/getClass', function(req, res, next) {
    co(function () {
        var params={};
        var paramT={};
        var paramU={};
        //根据id
        if(req.query.id != undefined){
            params["id"]=req.query.id;
        }
        //模糊查询
        if(req.query.cTitle != undefined){
            paramU["$like"]="%"+req.query.cTitle+"%";
            params["cTitle"]=paramU;
        }
        params["softDel"]=1;
        paramT["where"]=params;
        paramT["order"]=[["topTime",'DESC'],["createTime",'DESC']];
        console.log(paramT);
        seq.classModule.findAll(paramT).then(function(result){
            res.json({"success":true,"msg":"查询成功","result":result});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});

//修改新闻内容
router.get('/updateClass', function(req, res, next) {
    co(function () {
        var params={};
        var paramT={};
        var paramU={'id':req.query.id};
        if(req.query.cTitle != undefined){
            params["cTitle"]=req.query.cTitle;
        }
        if(req.query.cAbstract != undefined){
            params["cAbstract"]=req.query.cAbstract;
        }
        if(req.query.pUrl != undefined){
            params["url"]=req.query.pUrl;
        }
        if(req.query.softDel != undefined){
            params["softDel"]=req.query.softDel;
        }
        if(req.query.topTime!=0&&req.query.topTime!=""){
            params["topTime"]=moment().format("YYYY-MM-DD HH:mm:ss");
        }else {
            params["topTime"]=req.query.topTime;
        }
        paramT["where"]=paramU;
        seq.classModule.update(params,paramT
        ).then(function(results){
            res.json({"success":true,"msg":"修改成功","rows":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'修改失败'});
        console.log(e);
    })
});

router.post('/uploadImg', function(req, res, next) {
    co(function () {
        if (req.method.toLowerCase() == 'post') {
            // parse a file upload
            var form = new formidable.IncomingForm();
            //files = [],
            //fields = [];
            form.uploadDir = "public/img";
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                // res.render('index', { paths: [files.upload.name] });
                var imgType=files.pUrl.name.split(".");
                files.pUrl.name="class_"+moment().format("YYYYMMDDHHmmss"+"."+imgType[imgType.length-1]);
                fs.renameSync(files.pUrl.path, form.uploadDir + "/" + files.pUrl.name);
                fields.pUrl = files.pUrl.name;
                fields.createTime=moment().format("YYYY-MM-DD HH:mm:ss");
                seq.classModule.create(fields).then(function (results) {
                    res.redirect(getIP+'bigClass/bigClass.html');
                });
            });
        }
    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});

router.post('/updateImg', function(req, res, next) {
    co(function () {

        if (req.method.toLowerCase() == 'post') {
            // parse a file upload
            var form = new formidable.IncomingForm();
            //files = [],
            //fields = [];
            form.uploadDir = "public/img";
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                // res.render('index', { paths: [files.upload.name] });
                var params={};
                var paramT={};

                if(files.pUrl.name != ""){
                    var imgType=files.pUrl.name.split(".");
                    files.pUrl.name="class_"+moment().format("YYYYMMDDHHmmss"+"."+imgType[imgType.length-1]);
                    fs.renameSync(files.pUrl.path, form.uploadDir + "/" + files.pUrl.name);
                    params["pUrl"]=files.pUrl.name;
                }
                var paramU={'id':fields.id};

                if(fields.cTitle != undefined){
                    params["cTitle"]=fields.cTitle;
                }
                if(fields.url != undefined){
                    params["url"]=fields.url;
                }
                if(fields.cType != undefined){
                    params["cType"]=fields.cType;
                }
                paramT["where"]=paramU;

                seq.classModule.update(params,paramT).then(function (results) {
                    res.redirect(getIP+'bigClass/bigClass.html');
                });
            });
        }
    }).catch(function(e) {
        res.json({'success':false,'msg':'修改失败'});
        console.log(e);
    })
});

module.exports = router;